package com.bf.electroplating.controller;

import com.alibaba.excel.EasyExcel;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.bf.electroplating.job.CompanyDataSyncJob;
import com.bf.electroplating.job.RainfallMonthlyDataSyncJob;
import com.bf.electroplating.job.SewagePlantDailyDataGenerationJob;
import com.bf.electroplating.job.WarningDataSyncJob;
import com.bf.electroplating.pojo.dto.IdDTO;
import com.bf.electroplating.pojo.dto.company.ComCompanyDTO;
import com.bf.electroplating.pojo.entity.ComCompany;
import com.bf.electroplating.pojo.vo.ResultVO;
import com.bf.electroplating.pojo.vo.SelectVo;
import com.bf.electroplating.pojo.vo.attachment.AttachmentVo;
import com.bf.electroplating.pojo.vo.company.ComCompanyVO;
import com.bf.electroplating.service.ComCompanyService;
import com.bf.electroplating.service.PubAttachmentRelService;
import com.bf.electroplating.service.PubAttachmentService;
import com.bf.electroplating.util.easyexcel.excel.inflow.InflowDataExcel;
import com.bf.electroplating.util.easyexcel.excel.warning.WarningDataExcel;
import com.bf.electroplating.util.easyexcel.listener.InflowManageExcelListener;
import com.bf.electroplating.util.easyexcel.listener.WarningDataExcelListener;
import com.bf.electroplating.util.idempotent.Idempotent;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.Map;

@Slf4j
@RestController
@RequestMapping("/test")
@Tag(name = "内部测试接口", description = "内部测试接口")
public class TestController {

    @Autowired
    private ComCompanyService comCompanyService;
    
    @Autowired
    private WarningDataExcelListener warningDataExcelListener;

    @Resource
    private InflowManageExcelListener inflowManageExcelListener;
    @Resource
    private CompanyDataSyncJob companyDataSyncJob;
    @Resource
    private WarningDataSyncJob warningDataSyncJob;
    @Resource
    private SewagePlantDailyDataGenerationJob sewagePlantDailyDataGenerationJob;
    @Resource
    private com.bf.electroplating.util.easyexcel.listener.RectificationDataExcelListener rectificationDataExcelListener;
    
    @Resource
    private com.bf.electroplating.util.word.WordDocumentBatchProcessor wordDocumentBatchProcessor;
    @Resource
    private PubAttachmentService iPubAttachmentService;
    @Resource
    private RainfallMonthlyDataSyncJob rainfallMonthlyDataSyncJob;

    @PostMapping("/updateFile")
    @Operation(summary = "更新附件", description = "根据附件ID更新附件文件")
    public ResultVO<AttachmentVo> updateFile(@RequestParam("id") String id, MultipartFile file) throws IOException {
        return iPubAttachmentService.updateAttachment(id, file);
    }

    @PostMapping("/syncWeatherMonth")
    @Operation(summary = "企业雨排口--月度数据崇拜测试", description = "企业雨排口--月度数据崇拜测试")
    public ResultVO<String> syncWeatherMonth() {
        rainfallMonthlyDataSyncJob.syncRainfallMonthlyDataMonthly();
        return ResultVO.ok("");
    }

    @GetMapping("/enterpriseDataExchange")
    @Operation(summary = "企业数据转换", description = "企业数据转换")
    public ResultVO<String> enterpriseDataExchange() {
        com.alibaba.fastjson.JSONArray jsonArray = JSONArray.parseArray("[\n" +
                "        \n" +
                "        { lat: 28.870481, lng: 119.858427,title:'武义鑫润科技有限公司',description:'舒竞毅 15088279090',dz:'镀锌\u200C',cxNum:'12',number:'6',mb:'10001',content:'无'},\n" +
                "\n" +
                "        { lat: 28.873091, lng: 119.858797,title:'武义县宝恒电镀厂',description:'韩才壑 15727913939',dz:'镀镍',cxNum:'45',number:'12',mb:'10002',content:'无'},\n" +
                "        \n" +
                "        { lat: 28.870139, lng: 119.857093,title:'浙江恒辉工贸有限公司',description:'胡灵伟 13705899129',dz:'镀镉\u200C',cxNum:'22',number:'8',mb:'10003',content:'无'},\n" +
                "        \n" +
                "        { lat: 28.872922, lng: 119.860074,title:'武义弘泰金属机械有限公司',description:'卢正起 15257937369',dz:'镀铜\u200C',cxNum:'47',number:'20',mb:'10004',content:'无'},\n" +
                "       \n" +
                "        { lat: 28.872498, lng: 119.859963,title:'武义泓润工贸有限公司',description:'舒海明 13906765375',dz:'镀金',cxNum:'13',number:'4',mb:'10005',content:'无'},\n" +
                "        \n" +
                "        { lat: 28.870205, lng: 119.857735,title:'武义金闪工贸有限公司',description:'赵珠伟 15727946427',dz:'镀锌\u200C',cxNum:'12',number:'6',mb:'10006',content:'无'},\n" +
                "\n" +
                "        { lat: 28.872628, lng: 119.861277,title:'武义伟成电镀有限公司',description:'王  伟 15336912875',dz:'镀镍',cxNum:'45',number:'12',mb:'10007',content:'无'},\n" +
                "       \n" +
                "        { lat: 28.872290, lng: 119.861207,title:'武义鑫宏金属工艺品有限公司',description:'杜文彬 13605797288',dz:'镀镉\u200C',cxNum:'22',number:'8',mb:'10008',content:'无'},\n" +
                "        \n" +
                "        { lat: 28.872188, lng: 119.860396,title:'武义易欣五金有限公司',description:'项子良 13857924403',dz:'镀铜\u200C',cxNum:'47',number:'20',mb:'10009',content:'无'},\n" +
                "        \n" +
                "        { lat: 28.872440, lng: 119.862041,title:'浙江鸿泰工贸有限公司',description:'李一民 13905895583',dz:'镀金',cxNum:'13',number:'4',mb:'10010',content:'无'},\n" +
                "        \n" +
                "        { lat: 28.870534, lng: 119.859983,title:'浙江武义众誉工贸有限公司',description:'舒和平 13806775083',dz:'镀锌\u200C',cxNum:'12',number:'6',mb:'10011',content:'无'},  \n" +
                "\n" +
                "        { lat: 28.871224, lng: 119.852004,title:'武义县东方电镀厂',description:'王一浩 13967972908',dz:'镀镍',cxNum:'45',number:'8',mb:'10012',content:'无'},\n" +
                "\n" +
                "        { lat: 28.870962, lng: 119.854534,title:'武义县东升电镀有限公司',description:'陈雄伟 13905895990',dz:'镀镉\u200C',cxNum:'22',number:'6',mb:'10013',content:'无'},\n" +
                "\n" +
                "        { lat: 28.871204, lng: 119.850847,title:'武义县东方金属饰品厂',description:'吴  卫 13516937778',dz:'镀铜\u200C',cxNum:'47',number:'20',mb:'10014',content:'无'},\n" +
                "\n" +
                "        { lat: 28.871291, lng: 119.853285,title:'武义县兴盛电镀厂',description:'朱明双 13705892527',dz:'镀金',cxNum:'13',number:'4',mb:'10015',content:'无'},\n" +
                "\n" +
                "        { lat: 28.871462, lng: 119.860511,title:'浙江超洁工贸有限公司',description:'王平航 13905895276',dz:'镀锌\u200C',cxNum:'12',number:'6',mb:'10016',content:'无'},\n" +
                "        \n" +
                "        { lat: 28.873159, lng: 119.860609,title:'武义县新禹水处理有限公司',description:'陈伟法 18266979001',dz:'镀镍',cxNum:'45',number:'8',mb:'10017',content:'无'},\n" +
                "\n" +
                "        { lat: 28.872121, lng: 119.854238,title:'武义县碧水环保科技有限公司',description:'琚亮亮 18355182630',dz:'镀镉\u200C',cxNum:'22',number:'6',mb:'10018',content:'无'},\n" +
                "      ]");
        for (int i=0;i<jsonArray.size();i++){
            JSONObject jsonObject = jsonArray.getJSONObject(i);
            String companyName=jsonObject.getString("title");
            String lat=jsonObject.getString("lat");
            String lng=jsonObject.getString("lng");
            log.info("companyName:{}",companyName);
            log.info("lat:{}",lat);
            log.info("lng:{}",lng);
            ComCompany company=new ComCompany();
            company.setLongitude(Double.parseDouble(lng));
            company.setLatitude(Double.parseDouble(lat));
            comCompanyService.update(company,new LambdaQueryWrapper<ComCompany>().eq(ComCompany::getCompanyName,companyName));
        }
        return ResultVO.ok("");
    }


    @PostMapping("/syncWarningDataDaily")
    @Operation(summary = "预警数据同步测试", description = "预警数据同步测试")
    public ResultVO<String> syncWarningDataDaily() {
        warningDataSyncJob.syncWarningDataDaily();
        return ResultVO.ok("");
    }


    @PostMapping("/generateDailyBlankData")
    @Operation(summary = "日期生成", description = "日期生成")
    public ResultVO<String> generateDailyBlankData() {
        sewagePlantDailyDataGenerationJob.generateDailyBlankData();
        return ResultVO.ok("");
    }



    @PostMapping("/syncCompanyDataHourly")
    @Operation(summary = "企业数据同步测试", description = "syncCompanyDataHourly")
    public ResultVO<String> syncCompanyDataHourly() {
        companyDataSyncJob.syncCompanyDataHourly();
        return ResultVO.ok("");
    }
    
    @PostMapping("/excelImport")
    @Operation(summary = "预警数据导入", description = "预警数据导入")
    public ResultVO<String> excelImport(@RequestPart("file") MultipartFile file) {
        if (file == null || file.isEmpty()) {
            return ResultVO.fail("请选择要导入的Excel文件");
        }
        
        // 检查文件类型
        String fileName = file.getOriginalFilename();
        if (fileName == null || (!fileName.endsWith(".xlsx") && !fileName.endsWith(".xls"))) {
            return ResultVO.fail("请上传Excel文件(.xlsx或.xls格式)");
        }
        
        try {
            log.info("开始导入预警数据文件: {}", fileName);
            
            // 使用EasyExcel读取文件
            EasyExcel.read(file.getInputStream(), WarningDataExcel.class, warningDataExcelListener)
                    .sheet()
                    .headRowNumber(1) // 从第2行开始读取数据（第1行是表头）
                    .doRead();
            
            log.info("预警数据导入完成: {}", fileName);
            return ResultVO.ok("预警数据导入成功");
            
        } catch (IOException e) {
            log.error("预警数据导入失败: {}", e.getMessage(), e);
            return ResultVO.fail("文件读取失败: " + e.getMessage());
        } catch (Exception e) {
            log.error("预警数据导入异常: {}", e.getMessage(), e);
            return ResultVO.fail("导入失败: " + e.getMessage());
        }
    }

    @PostMapping("/InflowImport")
    @Operation(summary = "预警数据导入", description = "预警数据导入")
    public ResultVO<String> InflowImport(@RequestPart("file") MultipartFile file) {
        if (file == null || file.isEmpty()) {
            return ResultVO.fail("请选择要导入的Excel文件");
        }

        // 检查文件类型
        String fileName = file.getOriginalFilename();
        if (fileName == null || (!fileName.endsWith(".xlsx") && !fileName.endsWith(".xls"))) {
            return ResultVO.fail("请上传Excel文件(.xlsx或.xls格式)");
        }

        try {
            log.info("开始导入预警数据文件: {}", fileName);

            // 使用EasyExcel读取文件
            EasyExcel.read(file.getInputStream(), InflowDataExcel.class, inflowManageExcelListener)
                    .sheet()
                    .headRowNumber(1) // 从第2行开始读取数据（第1行是表头）
                    .doRead();

            log.info("预警数据导入完成: {}", fileName);
            return ResultVO.ok("预警数据导入成功");

        } catch (IOException e) {
            log.error("预警数据导入失败: {}", e.getMessage(), e);
            return ResultVO.fail("文件读取失败: " + e.getMessage());
        } catch (Exception e) {
            log.error("预警数据导入异常: {}", e.getMessage(), e);
            return ResultVO.fail("导入失败: " + e.getMessage());
        }
    }

    @PostMapping("/rectificationImport")
    @Operation(summary = "整改数据导入（含图片）", description = "整改数据导入，支持导入整改前后照片")
    public ResultVO<String> rectificationImport(
            @RequestPart("file") MultipartFile file,
            @RequestParam(value = "companyId", required = false) String companyId) {
        if (file == null || file.isEmpty()) {
            return ResultVO.fail("请选择要导入的Excel文件");
        }

        // 检查文件类型
        String fileName = file.getOriginalFilename();
        if (fileName == null || !fileName.endsWith(".xlsx")) {
            return ResultVO.fail("请上传Excel文件(.xlsx格式)");
        }

        try {
            log.info("开始导入整改数据文件: {}, 企业ID: {}", fileName, companyId);

            // 重要：每次导入前先重置监听器状态，清空上次导入的缓存数据
            rectificationDataExcelListener.reset();
            log.info("监听器状态已重置，准备开始新的导入");

            // 第一步：使用POI读取图片
            log.info("步骤1：读取Excel中的图片...");
            java.io.ByteArrayOutputStream baos = new java.io.ByteArrayOutputStream();
            file.getInputStream().transferTo(baos);
            byte[] fileBytes = baos.toByteArray();
            
            Map<String, String> imagePathMap = com.bf.electroplating.util.ExcelImageReader.readAndSaveImages(
                    new java.io.ByteArrayInputStream(fileBytes));
            log.info("成功读取{}张图片", imagePathMap.size());
            
            // 将图片路径和企业ID传递给监听器
            rectificationDataExcelListener.setImagePathMap(imagePathMap);
            rectificationDataExcelListener.setCompanyId(companyId);

            // 第二步：使用EasyExcel读取文本数据
            log.info("步骤2：读取Excel文本数据...");
            EasyExcel.read(new java.io.ByteArrayInputStream(fileBytes), 
                    com.bf.electroplating.util.easyexcel.excel.rectification.RectificationDataExcel.class, 
                    rectificationDataExcelListener)
                    .sheet()
                    .headRowNumber(1) // 从第2行开始读取数据（第1行是表头）
                    .doRead();

            log.info("整改数据导入完成: {}", fileName);
            return ResultVO.ok(String.format("整改数据导入成功，共处理%d张图片", imagePathMap.size()));

        } catch (IOException e) {
            log.error("整改数据导入失败: {}", e.getMessage(), e);
            return ResultVO.fail("文件读取失败: " + e.getMessage());
        } catch (Exception e) {
            log.error("整改数据导入异常: {}", e.getMessage(), e);
            return ResultVO.fail("导入失败: " + e.getMessage());
        }
    }

    @PostMapping("/wordRectificationImport")
    @Operation(summary = "Word整改数据批量导入", description = "从文件夹批量导入Word文档中的整改数据")
    public ResultVO<String> wordRectificationImport(@RequestParam("folderPath") String folderPath) {
        if (folderPath == null || folderPath.trim().isEmpty()) {
            return ResultVO.fail("请提供文件夹路径");
        }

        // 验证文件夹路径
        if (!wordDocumentBatchProcessor.validateFolderPath(folderPath)) {
            return ResultVO.fail("文件夹路径无效或不存在: " + folderPath);
        }

        try {
            log.info("开始批量导入Word整改数据，文件夹: {}", folderPath);

            // 检查文件夹中的Word文档数量
            int wordFileCount = wordDocumentBatchProcessor.getWordFileCount(folderPath);
            if (wordFileCount == 0) {
                return ResultVO.fail("文件夹中未找到Word文档(.docx文件)");
            }

            log.info("找到{}个Word文档，开始处理", wordFileCount);

            // 批量处理Word文档
            com.bf.electroplating.util.word.WordDocumentBatchProcessor.BatchProcessResult result = 
                wordDocumentBatchProcessor.processFolder(folderPath);

            if (result.isSuccess()) {
                String summary = String.format(
                    "Word整改数据批量导入成功！\n" +
                    "文件夹: %s\n" +
                    "处理文件: %d/%d (%.1f%%)\n" +
                    "处理记录: %d条 (成功%d条，失败%d条)\n" +
                    "成功率: %.1f%%\n" +
                    "企业匹配: %d个匹配成功，%d个使用原始名称",
                    result.getFolderName(),
                    result.getSuccessFiles(), result.getTotalFiles(), result.getSuccessRate(),
                    result.getTotalRecords(), result.getSuccessRecords(), result.getFailRecords(),
                    result.getRecordSuccessRate(),
                    result.getMatchedCompanyCount(), result.getUnmatchedCompanyCount()
                );

                log.info("Word整改数据批量导入完成: {}", result.getSummary());
                return ResultVO.ok(summary);
            } else {
                log.error("Word整改数据批量导入失败: {}", result.getErrorMessage());
                return ResultVO.fail("批量导入失败: " + result.getErrorMessage());
            }

        } catch (Exception e) {
            log.error("Word整改数据批量导入异常: {}", e.getMessage(), e);
            return ResultVO.fail("导入异常: " + e.getMessage());
        }
    }

    @GetMapping("/wordRectificationPreview")
    @Operation(summary = "Word文档预览", description = "预览文件夹中的Word文档信息")
    public ResultVO<String> wordRectificationPreview(@RequestParam("folderPath") String folderPath) {
        if (folderPath == null || folderPath.trim().isEmpty()) {
            return ResultVO.fail("请提供文件夹路径");
        }

        // 验证文件夹路径
        if (!wordDocumentBatchProcessor.validateFolderPath(folderPath)) {
            return ResultVO.fail("文件夹路径无效或不存在: " + folderPath);
        }

        try {
            int wordFileCount = wordDocumentBatchProcessor.getWordFileCount(folderPath);
            
            String preview = String.format(
                "文件夹预览: %s\n" +
                "Word文档数量: %d个\n" +
                "支持的格式: .docx\n" +
                "注意: 请确保每个Word文档格式正确（第一行公司名称，第二行开始为表格）",
                folderPath, wordFileCount
            );

            return ResultVO.ok(preview);

        } catch (Exception e) {
            log.error("预览Word文档失败: {}", e.getMessage(), e);
            return ResultVO.fail("预览失败: " + e.getMessage());
        }
    }

    @GetMapping("/wordCompanyMatchingPreview")
    @Operation(summary = "Word企业匹配预览", description = "预览Word文档中的企业名称匹配情况")
    public ResultVO<String> wordCompanyMatchingPreview(@RequestParam("folderPath") String folderPath) {
        if (folderPath == null || folderPath.trim().isEmpty()) {
            return ResultVO.fail("请提供文件夹路径");
        }

        // 验证文件夹路径
        if (!wordDocumentBatchProcessor.validateFolderPath(folderPath)) {
            return ResultVO.fail("文件夹路径无效或不存在: " + folderPath);
        }

        try {
            Map<String, String> matchingResults = wordDocumentBatchProcessor.previewCompanyMatching(folderPath);
            
            StringBuilder preview = new StringBuilder();
            preview.append("=== 企业匹配预览 ===\n");
            preview.append("文件夹: ").append(folderPath).append("\n");
            preview.append("文档数量: ").append(matchingResults.size()).append("个\n\n");
            
            preview.append("企业名称匹配情况:\n");
            for (Map.Entry<String, String> entry : matchingResults.entrySet()) {
                preview.append("📄 ").append(entry.getKey())
                       .append(" -> 🏢 ").append(entry.getValue()).append("\n");
            }
            
            preview.append("\n注意: 导入时会自动匹配com_company表中的企业信息");

            return ResultVO.ok(preview.toString());

        } catch (Exception e) {
            log.error("预览企业匹配失败: {}", e.getMessage(), e);
            return ResultVO.fail("预览失败: " + e.getMessage());
        }
    }

    @GetMapping("/wordErrorAnalysis")
    @Operation(summary = "Word导入错误分析", description = "分析Word导入失败的原因")
    public ResultVO<String> wordErrorAnalysis(@RequestParam("folderPath") String folderPath) {
        if (folderPath == null || folderPath.trim().isEmpty()) {
            return ResultVO.fail("请提供文件夹路径");
        }

        // 验证文件夹路径
        if (!wordDocumentBatchProcessor.validateFolderPath(folderPath)) {
            return ResultVO.fail("文件夹路径无效或不存在: " + folderPath);
        }

        try {
            // 这里可以添加错误分析逻辑
            // 暂时返回提示信息
            String analysis = "错误分析功能开发中，请查看日志文件获取详细错误信息：\n" +
                            "1. 查看运行日志: tail -f running.log | grep -E '(❌|跳过无效数据)'\n" +
                            "2. 常见失败原因:\n" +
                            "   - 必填字段为空（车间、具体点位、问题描述、公司名称）\n" +
                            "   - 表格列名不匹配\n" +
                            "   - 数据格式异常\n" +
                            "   - 数据库保存异常\n" +
                            "   - 图片处理异常";

            return ResultVO.ok(analysis);

        } catch (Exception e) {
            log.error("错误分析失败: {}", e.getMessage(), e);
            return ResultVO.fail("错误分析失败: " + e.getMessage());
        }
    }


} 